<template>
<!--  头部-->
  <div class="container-login">
    <van-nav-bar
      title="登录"
      left-arrow
      @click-left="$router.back()"
    />
<!--    表单-->
    <van-form
      validate-first
      :show-error="false"
      :show-error-message="false"
      @submit="onLogin"
      @failed="onFailed"
      ref="loginRef"
    >
      <van-field
        name="mobile"
        v-model="user.mobile"
        icon-prefix="danger"
        left-icon="shouji"
        placeholder="请输入手机号"
        :rules=formRulers.mobile
      />
      <van-field
        center
        name="code"
        v-model="user.code"
        clearable
        icon-prefix="danger"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        :rules=formRulers.code
      >
        <template #button>
          <van-count-down v-if="isCountDownShow" :time="60*1000" format="ss 秒" @finish="isCountDownShow = false" />
          <van-button v-else class="code-button" :loading="isSendLoading" size="small" round @click.prevent="onSendSms">获取验证码</van-button>
        </template>
      </van-field>
      <!--    按钮-->
      <div class="button-wrap">
        <van-button type="info" block >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from '../../api/user.js'
export default {
  name: 'loginIndex',
  data () {
    return {
      user: {
        mobile: '',
        code: ''
      },
      formRulers: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          { pattern: /^1\d{10}$/, message: '手机号格式不正确' }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          { pattern: /^\d{6}$/, message: '验证码格式不正确' }
        ]
      },
      isCountDownShow: false, // 倒计时按钮显示状态
      isSendLoading: false // 发送验证码按钮loading状态
    }
  },
  methods: {
    onLogin: async function () {
      this.$toast.loading({
        message: '登录中...', // 文本内容，支持通过\n换行
        forbidClick: true, // 是否禁止背景点击
        duration: 0 // 展示时长(ms)，值为 0 时，toast 不会消失
      })
      try {
        const { data } = await login(this.user)
        this.$toast.success('登录成功！')
        // 将后端返回的用户登录状态（token 等数据）放到 Vuex 中
        this.$store.commit('setUser', data.data)
        // 在离开登录页面之前，将 layout 组件从缓存配置中删除，以重新加载该组件
        this.$store.commit('removeCachePage', 'layoutIndex')
        // 跳转页面
        /*
          实现从哪来回哪去，或回首页
          比 this.$router.back() 要严谨
         */
        this.$router.push(this.$route.query.returnUrl || '/')
      } catch (e) {
        this.$toast.fail('登陆失败！')
      }
    },
    onFailed: function (res) {
      if (res.errors[0]) {
        this.$toast({
          message: res.errors[0].message,
          position: 'top'
        })
      }
    },
    onSendSms: async function () {
      var message = ''
      this.isSendLoading = true // 按钮loading状态
      // mobile 验证
      await this.$refs.loginRef.validate('mobile')
        .catch(error => { // 验证未通过
          message = error.message
        })
      // 验证通过
      if (!message) {
        this.isCountDownShow = true // 显示倒计时按钮
        await sendSms(this.user.mobile)
          .then(res => { // 发送成功
            console.log(res)
          })
          .catch(error => {
            if (error.response && error.response.status === 429) {
              message = '发送太频繁，请稍后重试！'
              console.log('pin', message)
            }
            // 未知错误
            message = '发送失败，请稍后重试！'
            console.log('wei', message)
          })
      }
      // 弹出提示
      if (message) {
        this.$toast({
          message,
          position: 'top'
        })
      }
      this.isSendLoading = false // 取消按钮loading状态
    }
  }
}
</script>

<style scoped>
  .code-button {
    color: #666666;
    font-size: 11px;
    background-color: #ededed;
  }
  .button-wrap {
    padding: 53px 28px;
  }
  .button-wrap button {
    border-radius: 5px;
    background-color: #6db4fb;
  }
</style>
